package com.example.testgame.handlers;

import java.util.ArrayList;
import java.util.List;

import android.os.Handler;
import android.os.Message;

import com.example.testgame.sys.Constant;
import com.example.testgame.sys.Variable;
import com.example.testgame.util.GameHelper;
/**
 * 缩放控制Handler
 * @author wolf_jr
 *
 */
public class ZoomHandler extends Handler {
	
	private static final long INTERVAL = 40;
	
	private static ZoomHandler instance = new ZoomHandler();
	
	private List<OnZoomChangeListener> listenerList;
	
	private ZoomHandler() {
		listenerList = new ArrayList<ZoomHandler.OnZoomChangeListener>();
	}
	
	@Override
	public void handleMessage(Message msg) {
		float goal = (Float) msg.obj;
		int col = msg.arg1;
		int row = msg.arg2;
		if(goal != Variable.zoom) {
			// 改变比例
			float dz = goal - Variable.zoom;
			float _dz;
			if(Math.abs(dz) > 0.2f) {
				_dz = dz / 4;
				if(Math.abs(_dz) < 0.2f) 
					_dz = dz > 0 ? 0.2f : -0.2f;
			}else {
				_dz = dz;
			}
			Variable.zoom += _dz;
			// 改变偏移
			Variable.offsetX -= _dz * col * Constant.BLOCK_WIDTH;
			Variable.offsetY -= _dz * row * Constant.BLOCK_HEIGHT;
			notifyZoomChanged();
			Message _msg = obtainMessage(0, col, row, msg.obj);
			sendMessageDelayed(_msg, INTERVAL);
		}
	}
	
	private void notifyZoomChanged() {
		for (OnZoomChangeListener listener : listenerList) {
			listener.onZoomChange();
		}
	}
	
	/**
	 * 开始缩放到指定比例
	 * @param zoom
	 */
	public static void startZoomTo(float zoom, int x, int y) {
		instance.removeMessages(0);
		Message msg = instance.obtainMessage(0, GameHelper.getColByX(x), GameHelper.getRowByY(y), zoom);
		instance.sendMessage(msg);
	}
	
	/**
	 * 添加比例改变时的监听
	 * @param listener
	 */
	public static void addOnZoomChangeListener(OnZoomChangeListener listener) {
		if(listener != null) {
			instance.listenerList.add(listener);
		}
	}
	
	
	/**
	 * 当比例改变时的回调
	 * @author wolf_jr
	 *
	 */
	public static interface OnZoomChangeListener {
		void onZoomChange();
	}

}
